package com.zxb.base.watch.util;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author Zxb
 * 线程工具类
 */
class ControllableThread extends Thread {
    private volatile boolean running = true;
    private volatile boolean paused = false;
    private final Lock lock = new ReentrantLock();
    private final Condition condition = lock.newCondition();

    @Override
    public void run() {
        lock.lock();
        try {
            while (running) {
                while (paused) {
                    try {
                        condition.await();
                    } catch (InterruptedException e) {
                        Thread.currentThread().interrupt();
                        return;
                    }
                }

                // 模拟线程的工作
                System.out.println("Thread is running...");
                try {
                    // 休眠1秒
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                    return;
                }
            }
        } finally {
            lock.unlock();
        }
        System.out.println("Thread is stopping...");
    }

    public void pauseThread() {
        lock.lock();
        try {
            paused = true;
        } finally {
            lock.unlock();
        }
    }

    public void resumeThread() {
        lock.lock();
        try {
            paused = false;
            condition.signalAll();
        } finally {
            lock.unlock();
        }
    }

    public void stopThread() {
        lock.lock();
        try {
            running = false;
            paused = false;
            condition.signalAll();
        } finally {
            lock.unlock();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        ControllableThread thread = new ControllableThread();
        thread.start();

        // 等待3秒 暂停线程
        Thread.sleep(3000);
        thread.pauseThread();
        System.out.println("Thread is paused.");

        // 等待3秒 恢复线程
        Thread.sleep(3000);
        thread.resumeThread();
        System.out.println("Thread is resumed.");

        // 等待3秒 停止线程
        Thread.sleep(3000);
        thread.stopThread();
        System.out.println("Thread is requested to stop.");

        // 等待线程真正停止
        thread.join();
        System.out.println("Thread has stopped.");
    }
}
